
package sample.multithreading;

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.os.Process;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.Vector;

/**
 * This service is really a generic HTTP downloader. It will pull the content of
 * the passed-in URL and broadcast the state of the world to the application.
 */
public class NetworkDownloadTask extends AsyncTask<URL, Integer, Vector<URL[]>> implements
        ProgressNotifier {
    public static final String BROADCAST_ACTION = "sample.downloader.PicasaContentDB";
    public static final String EXTRA_LOG = "PS.LOG";
    public static final String EXTRA_STATUS = "PS.EXS";
    public static final String LOG_TAG = "PicasaService";
    public static final int STATE_ACTION_STARTED = 0;
    public static final int STATE_ACTION_CONNECTING = 1;
    public static final int STATE_ACTION_PARSING = 2;
    public static final int STATE_ACTION_COMPLETE = 3;
    public static final int STATE_LOG = -1;

    private final DownloaderActivity mActivity;
    
    // a reasonable user-agent string
    private static final String USER_AGENT = "Mozilla/5.0 (Linux; U; Android " + android.os.Build.VERSION.RELEASE + ";" + Locale.getDefault().toString() + "; " + android.os.Build.DEVICE + "/" + android.os.Build.ID + ")";

    public NetworkDownloadTask(DownloaderActivity activity) {
        super();
        mActivity = activity;
    }
    
    /*
     * Used for logging from the pull parser
     * @see sample.multithreading.asynctask.ProgressNotifier#notifyProgress(java.lang.String)
     */
    public void notifyProgress(String paramString) {
        
    }   
    
    /**
     * This happens in the UI (main) thread resulting from onProgressUpdate
     */
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        switch(values[0]) {
            case STATE_ACTION_STARTED:
                mActivity.setProgressText(R.string.progress_starting_update);
                mActivity.showProgress(true);
                break;
            case STATE_ACTION_CONNECTING:
                mActivity.setProgressText(R.string.progress_connecting);
                mActivity.showProgress(true);
                break;
            case STATE_ACTION_PARSING:
                mActivity.setProgressText(R.string.progress_parsing);
                mActivity.showProgress(true);
                break;
            case STATE_ACTION_COMPLETE:
                mActivity.showProgress(false);
                break;
            }
    }

    @Override
    protected Vector<URL[]> doInBackground(URL... params) {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        URL localURL = params[0];
        try {
            URLConnection localURLConnection = localURL.openConnection();
            if ((localURLConnection instanceof HttpURLConnection)) {
                publishProgress(STATE_ACTION_STARTED);
                HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;
                localHttpURLConnection
                        .setRequestProperty(
                                "User-Agent",
                                USER_AGENT);
                publishProgress(STATE_ACTION_CONNECTING);
                localHttpURLConnection.getResponseCode();
                publishProgress(STATE_ACTION_PARSING);
                PicasaPullParser localPicasaPullParser = new PicasaPullParser();
                localPicasaPullParser.parseXml(
                        localURLConnection.getInputStream(), this);
                publishProgress(STATE_ACTION_COMPLETE);
                return localPicasaPullParser.getImages();
            }
        } catch (MalformedURLException localMalformedURLException) {
            localMalformedURLException.printStackTrace();
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        } catch (XmlPullParserException localXmlPullParserException) {
            localXmlPullParserException.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Vector<URL[]> result) {
        super.onPostExecute(result);
        mActivity.setResult(result);
    }
    
    
}
